package mahan.data.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mahan.data.core.Util;

import org.bson.BSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mongodb.DBObject;

public class ShoppingCart implements KeyValuePair {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static ShoppingCart from(DBObject dbo) {
		Map map = dbo.toMap();
		ShoppingCart cart = new ShoppingCart((Integer) map.get("cid"));
		cart.put(map);
		return cart;
	}

	private List<Object> items = new ArrayList<Object>();

	private int custID;

	public ShoppingCart(int custid) {
		this.custID = custid;
	}

	public void add(CartLineItem cli) {
		items.add(Util.convert(cli));
	}

	public Map<String, ?> get() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cid", custID);
		map.put("i", items);
		return map;
	}

	public List<CartLineItem> getItems() {
		List<CartLineItem> list = new ArrayList<CartLineItem>();
		for (Object item : items) {
			list.add(Util.getCartItem((BSONObject) item));
		}
		return list;
	}

	public JSONObject json() throws JSONException {
		JSONObject json = new JSONObject();
		json.put("cid", custID);
		JSONArray jsonArr = new JSONArray(items);
		json.put("i", jsonArr);
		return json;
	}

	@SuppressWarnings("unchecked")
	public void put(Map<String, ?> map) {
		items.clear();
		items.addAll((Collection<Object>) map.get("i"));
	}
}